<template>
  <div class="wrapper">
    <el-header class="frontPage_header">
      <el-row :gutter="10">
        <el-col :xs="24" :lg="4">
          <div class="header_left">
            <img
              src="../../assets/logo.png"
              alt
              class="header_logo"
              @click="navToFront"
              style="cursor:pointer"
            >
            <span class="logo_text" @click="navToFront" style="cursor:pointer">好课优评</span>
          </div>
        </el-col>
        <el-col :xs="24" :lg="8" style="height:44px;line-height:44px">
          <div class="web_slogen">
            <span class="iconfont" style="font-size:20px">&#xe60d;</span>
            <span style="cursor:pointer" @click="navToFront">To be a better man!</span>
          </div>
        </el-col>
        <el-col :xs="24" :lg="8" style="position:relative">
          <el-input placeholder="请输入课程平台/课程标题" v-model="search" @keyup.enter.native="searchItem"></el-input>
          <span class="el-icon-error clear" v-show="search" @click="clear"></span>
          <span class="el-icon-search search" @click="searchItem"></span>
        </el-col>
        <el-col :xs="24" :lg="4" style="height:44px;line-height:44px;padding-right:60px">
          <div class="personalCenter">
            <div v-show="userlogin" class="ellipse">
              <span class="title_span" @click="personalCenter">
                <i class="fa fa-user-circle"></i>
                {{name}}
              </span>
              <span class="title_span" @click="loginout" style="margin-left:10px;color:#409EFF">退出</span>
            </div>
            <div v-show="!userlogin">
              <el-button type="text" @click="showModal(1)">登录</el-button>
              <el-button type="text" @click="showModal(2)">注册</el-button>
            </div>
            <div>
              <modal
                name="sign-in"
                transition="pop-out"
                :width="modalWidth"
                :height="600"
                resizable
                draggable
              >
                <div class="box">
                  <span class="el-icon-close closemodal" @click="hideModal"></span>
                  <div>
                    <img src="../../assets/logo.png" alt class="header_logo">
                  </div>
                  <div>To be a better man!</div>
                  <el-form
                    ref="form"
                    :model="form"
                    label-width="80px"
                    style="margin-top:30px"
                    :rules="rules"
                  >
                    <el-form-item label="邮箱" style="margin-bottom:50px" prop="email">
                      <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="pwd" v-show="!forgetPassWord">
                      <el-input v-model="form.pwd" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="pwd1" v-if="showSign&&!forgetPassWord">
                      <el-input v-model="form.pwd1" placeholder="请再次输入密码"></el-input>
                    </el-form-item>
                    <div class="centerModal">
                      <el-button
                        type="primary"
                        style="width:520px;"
                        v-if="!showSign&&!forgetPassWord"
                        @click="login('form',form)"
                      >登陆</el-button>
                      <el-button
                        type="primary"
                        style="width:520px;"
                        v-if="forgetPassWord"
                        @click="sentforgetEmail(form)"
                      >重置密码</el-button>
                      <el-button
                        type="primary"
                        style="width:520px;"
                        v-else
                        @click="register(form)"
                      >注册</el-button>
                      <el-form-item
                        v-if="showSign"
                        style="text-align:left;font-size:13px;color:909399"
                        prop="checked"
                      >
                        <el-checkbox-group v-model="form.checked">
                          <el-checkbox label="同意《用户协议》及隐私政策" name="checked"></el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>
                      </div>
                      <div>
                        <el-button
                          type="text"
                          style="float:left;color:#909399"
                          v-if="!showSign&&!forgetPassWord"
                          @click="forgetPassWords"
                        >忘记密码？</el-button>
                        <el-button
                          type="text"
                          style="float:right"
                          @click="showSign=true"
                          v-show="!showSign&&!forgetPassWord"
                        >注册</el-button>
                        <div style="clear:both"></div>
                      </div>
                      <div style="text-align:right" v-show="showSign">
                        <el-button type="text" @click="showSign=false">已有账号，去登陆</el-button>
                      </div>
                  </el-form>
                </div>
              </modal>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="10"></el-row>
    </el-header>
  </div>
</template>

<script>
import { login, register, getUserInfo } from "@/api/ajax";
import axios from "axios";
export default {
  name: "Header",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.pwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.pwd1 !== "") {
          this.$refs.form.validateField("pwd1");
        } else {
          var pattern = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/;
          if (!pattern.test(value)) {
            callback(new Error("密码应包含数字、大小写字母、特殊字符"));
          }
        }
        callback();
      }
    };
    return {
      search: "",
      name: "",
      modalWidth: "600px",
      forgetPassWord: false,
      showSign: false,
      dialogVisible: false,
      userlogin: false,
      form: {
        email: "",
        checked: [],
        pwd1: "",
        pwd: ""
      },
      rules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: ["blur", "change"]
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        pwd: [{ validator: validatePass1, trigger: "blur" }],
        pwd1: [{ validator: validatePass, trigger: ["blur", "change"] }],
        checked: [
          {
            type: "array",
            required: true,
            message: "请确认同意用户协议",
            trigger: "change"
          }
        ]
      }
    };
  },
  components: {},
  methods: {
    clear: function() {
      this.search = "";
    },
    forgetPassWords: function() {
      this.forgetPassWord = true;
    },
    checklogin: function() {
      if (localStorage.getItem("token")) {
        this.userlogin = true;
        this.name = localStorage.getItem("name");
      } else {
        this.userlogin = false;
      }
    },
    loginout() {
      localStorage.clear();
      this.userlogin = false;
    },
    sentforgetEmail: function() {},
    navToFront: function() {
      this.$router.push({ path: "/" });
    },
    showModal: function(v) {
      if (v == 2) {
        this.showSign = true;
      }
      this.$modal.show("sign-in");
    },
    hideModal: function() {
      this.$modal.hide("sign-in");
      this.$refs.form.resetFields();
    },
    personalCenter: function() {
      this.$router.push({ name: "PersonalCenter" });
    },
    searchItem() {
      if (this.search) {
        this.$router.push({
          name: "SearchItem",
          query: { searchresult: this.search }
        });
      }
    },
    login(name,form) {
      this.$refs[name].validate(valid => {
        // if (valid) {
          var params = {};
          params.email = form.email;
          params.password = form.pwd;
          axios({
            method: "post",
            url: "account/a/h/login",
            data: params,
            headers: {
              "Content-type": "application/json"
            }
          }).then(res => {
            if (res.data.code == 0) {
              this.$message({
                message: "登陆成功",
                type: "success"
              });
              this.$store.dispatch("setUserName", form.email);
              this.$store.dispatch("setToken", res.data.data.token);
              this.userlogin = true;
              this.$modal.hide("sign-in");
              this.checklogin();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        // } else {
        //   console.log("error submit!!");
        //   return false;
        // }
      });
    },
    register(form) {
      var params = {};
      params.email = form.email;
      params.password = form.pwd;
      this.$refs["form"].validate(valid => {
        if (valid) {
          axios({
            method: "post",
            url: "account/a/h/register",
            data: params,
            headers: {
              "Content-type": "application/json"
            }
          }).then(res => {
            if (res.data.code == 0) {
              this.$message({
                message: "注册成功，请登录邮箱激活账号",
                type: "success"
              });
              this.showSign = false;
            } else {
              this.$message.error("抱歉，注册失败");
            }
          });
        } else {
          return false;
        }
      });
    }
  },
  mounted() {
    this.checklogin();
  },
  created() {
    var self = this;
    this.$bus.$on("loginModal", function() {
      self.showModal();
    });
  }
};
</script>

<style lang="less" scoped>
@import "~styles/z.less";
@import "~styles/css3.less";
@import "~styles/variables.less";

.wrapper {
  .frontPage_header {
    margin-top: 20px;
    .centerModal{
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height:200px;
      align-items: center;
    }
    .title_span {
      &:hover {
        color: orange;
      }
    }
    .header_left {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .header_logo {
        width: 44px;
        height: 44px;
      }
      .logo_text {
        .MainFont;
        margin-left: 10px;
      }
    }
    .web_slogen {
      .tc;
      .MainFont;
    }
    .clear {
      .abs;
      top: 13px;
      cursor: pointer;
      right: 40px;
      .font-s(17px);
      color: grey;
    }
    .search {
      .abs;
      top: 13px;
      cursor: pointer;
      right: 15px;
      .font-s(17px);
      color: grey;
    }
    .personalCenter {
      .MainFont;
      .ellipse {
        white-space: nowrap;
        width: 240px;
        font-size: 15px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      text-align: center;
      font-family: Tahoma;
      cursor: pointer;
      .box {
        padding: 40px;
        text-align: center;
        .rel;
        .closemodal {
          .abs;
          right: 20px;
          top: 20px;
        }
        .header_logo {
          width: 54px;
          height: 54px;
        }
      }
      .pop-out-enter-active,
      .pop-out-leave-active {
        transition: all 2s;
      }
      .pop-out-enter,
      .pop-out-leave-active {
        opacity: 0;
        transform: translateY(24px);
      }
    }
  }
}
</style>
